﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Redirection
{
    [Serializable]
    public class RedirectionInfo
    {
        private string _destination;
        private string _source;
        private SPSite Site;

        public RedirectionInfo(SPSite site, string source, string destination, bool permanent)
        {
            Site = site;
            Source = source;
            Destination = destination;
            IsPermanent = permanent;
        }

        public RedirectionInfo(SPListItem item)
        {
            Source = item[ConstantsService.Fields.RequestedUrlFieldId] != null
                         ? item[ConstantsService.Fields.RequestedUrlFieldId].ToString()
                         : string.Empty;
            Destination = item[ConstantsService.Fields.DestinationUrlFieldId] != null
                              ? item[ConstantsService.Fields.DestinationUrlFieldId].ToString()
                              : string.Empty;
            if (item[ConstantsService.Fields.PermanentRedirectFieldId] == null) return;

            bool b;
            bool.TryParse(item[ConstantsService.Fields.PermanentRedirectFieldId].ToString(), out b);
            IsPermanent = b;

            Site = item.ParentList.ParentWeb.Site;
        }

        public string Source
        {
            get
            {
                return Uri.IsWellFormedUriString(_source, UriKind.Relative)
                            ? string.Format("{0}/{1}", Site.ServerRelativeUrl != "/" ? Site.ServerRelativeUrl : string.Empty, _source.TrimStart(new[] { '/' }))
                            : _source;
                
            }
            private set { _source = value.TrimStart(new[] {'/'}); }
        }

        public string OriginalSource
        {
            get 
            {
                return _source;
            }
        }

        public string OriginalDestination
        {
            get
            {
                return _destination;
            }
        }

        public string Destination
        {
            get
            {
                return Uri.IsWellFormedUriString(_destination, UriKind.Relative)
                           ? string.Format("{0}/{1}", Site.ServerRelativeUrl != "/" ? Site.ServerRelativeUrl : string.Empty, _destination.TrimStart(new[] { '/' }))
                           : _destination;
            }
            private set { _destination = value.TrimStart(new[] {'/'}); }
        }

        public bool IsPermanent { get; private set; }
    }
}